﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using Common.DataTypes;
using LinqAmazonProvider;
using System.Windows.Threading;
using System.Text.RegularExpressions;
using SilverlightApplication1.DataTypes;
using SilverlightApplication1;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        public static ManualResetEvent alldone;
        public static bool validKey;
        private Dictionary<int, string> languageTranslator = new Dictionary<int, string>();
        private Dispatcher _mainDispatcher;
        private List<Common.DataTypes.Book> lstQueryResult = new List<Book>();
        private DTSearchCriteria advanced;
        private int language;
        private string passwordAmazon;
        private Boolean passwordChanged;

        const int ITEMS_PER_PAGE = 5;

        /***************************/
        private int totalPages;
        private int actualPage;
        private int totalItems;
        /***************************/

        // Atributo sobre el que ejecutaremos las busquedas
        // Amazon Search parameters
        private string searchKeyword; //TODO:: cambiar este atributo para que sea una estructura con toda la info
        //de la query a realizar.

        public List<Book> QueryResult
        {
            get
            {
                return lstQueryResult;
            }
            set
            {
                lstQueryResult = value;
            }
        }

        //TODO:: Cambiar el tipo de la Propiedad por la estructura a definir
        public DTSearchCriteria SearchCriteria { get; set; }


        public Page()
        {
            InitializeComponent();
            this.Loaded += (object sender, RoutedEventArgs e) => { anims.Begin(); };

            BrdLayoutRoot.Visibility = Visibility.Collapsed;
            BaseLayoutRoot.Visibility = Visibility.Collapsed;
            icMoreInfoPopUp.Visibility = Visibility.Collapsed;
            //SignInPopUp.Visibility = Visibility.Visible;
            PopUpKey.Visibility = Visibility.Visible;

            //BrdLayoutRoot.Visibility = Visibility.Collapsed;
            //BaseLayoutRoot.Visibility = Visibility.Collapsed;
            //icMoreInfoPopUp.Visibility = Visibility.Collapsed;
            //SignInPopUp.Visibility = Visibility.Visible;
            
            // Load language dictionary
            languageTranslator.Add(1, "ingles");
            languageTranslator.Add(2, "espaniol");
            
            PopPup();
            Show();

            //TODO::Revisar comentario no es correcto y es confuso.
            // Se crea el Searcher y se crea el evento que maneja la finalizacion de la busqueda
            // Create searcher and event to handle search finalization event
            this._mainDispatcher = MainDispatcher.Current;

            advanced = new DTSearchCriteria();

            passwordAmazon = "";
            passwordChanged = true;

            language = 1;    //English
            SetLanguage();

            txtQuery.TabIndex = 0;

            actualPage = 1;
            totalPages = 1;
            totalItems = 0;
        }

        #region Search Functions

        void SearcherFnc()
        {
            //PopUpBox.Visibility = Visibility.Collapsed;
            //PopUpLoading.Visibility = Visibility.Visible;
            PopUpKey.Visibility = Visibility.Collapsed;
            PopUpBox.Visibility = Visibility.Collapsed;
            PopUpLoading.Visibility = Visibility.Visible;
            PopPup();
            Show();
            SBLoad.Begin();

            //TODO::Eliminar ya que no es necesario ya que no es siempre la misma lista
            //this.lstResult.Items.Clear();

            //TODO: Creacion de SearchCriteria
            // Amazon Search parameter
            //advanced.mainKeywords = this.txtQuery.Text;

            try
            {
                // Perform Amazon search
                //PerformSearch(keyword);

                // Create thread to perform the amazon search
                Thread worker = new Thread(new ThreadStart(GetLINQResult));

                //TODO:: Cambiar a set de Criteria objeto con toda la info de la busqueda. (No solo Keyword)
                // Set the static parameter Keyword
                SearchCriteria = advanced; //searchKeyword = keyword;
                worker.Start();
            }

            catch (Exception ex)
            {
                // TODO manejar excepcion
            }
        }

        private void GetLINQResult()
        {
            try
            {
                //TODO::esto se tiene que ir
                List<Book> result = new List<Book>();

                // Create provider, set the Amazon key and language
                var provider = new AmazonProvider();
                provider.AmazonKey = passwordAmazon;
                provider.ResultLanguage = languageTranslator[language];

                var queryable = new AmazonQuery<Book>(provider);

                int numberItemsToSkip = ITEMS_PER_PAGE * (actualPage - 1);
                if (SearchCriteria.isAdvanced)
                {
                    #region Advanced Search
                    int minPrice = decimal.ToInt32(SearchCriteria.minPrice);
                    int maxPrice = decimal.ToInt32(SearchCriteria.maxPrice);
                    string bookCondition = SearchCriteria.condition;

                    var query =
                        from book in queryable
                        where
                          book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                          book.Title == SearchCriteria.title && book.Condition == bookCondition && book.Category == SearchCriteria.category &&
                          book.ListPrice.Amount >= minPrice && book.ListPrice.Amount <= maxPrice &&
                          book.Keywords == SearchCriteria.keywords
                        select book;

                    if (newSearch)
                    {
                        totalItems = query.Count<Book>();
                    }

                    query = query.Skip<Book>(numberItemsToSkip).Take<Book>(ITEMS_PER_PAGE);

                    if (SearchCriteria.sortBy.isSortConditionSelected)
                    {
                        #region Add Sort Criteria
                        switch (SearchCriteria.sortBy.firstSortCondition)
                        {
                            case DTSearchCriteria.LST_PRICE_ASC:
                                query = query.OrderBy("ListPrice", false);
                                break;
                            case DTSearchCriteria.LST_PRICE_DSC:
                                query = query.OrderBy("ListPrice", true);
                                break;
                            case DTSearchCriteria.PUB_DATE:
                                query = query.OrderBy("PublicationDate", false);
                                break;
                            case DTSearchCriteria.TITLE:
                                query = query.OrderBy("Title", false);
                                break;
                        }

                        if (SearchCriteria.sortBy.isSecondConditionSelected)
                        {
                            switch (SearchCriteria.sortBy.secondSortCondition)
                            {
                                case DTSearchCriteria.LST_PRICE_ASC:
                                    query = query.OrderBy("ListPrice", false);
                                    break;
                                case DTSearchCriteria.LST_PRICE_DSC:
                                    query = query.OrderBy("ListPrice", true);
                                    break;
                                case DTSearchCriteria.PUB_DATE:
                                    query = query.OrderBy("PublicationDate", false);
                                    break;
                                case DTSearchCriteria.TITLE:
                                    query = query.OrderBy("Title", false);
                                    break;
                            }
                        }

                        if (SearchCriteria.sortBy.isThirdConditionSelected)
                        {
                            switch (SearchCriteria.sortBy.thirdSortCondition)
                            {
                                case DTSearchCriteria.LST_PRICE_ASC:
                                    query = query.OrderBy("ListPrice", false);
                                    break;
                                case DTSearchCriteria.LST_PRICE_DSC:
                                    query = query.OrderBy("ListPrice", true);
                                    break;
                                case DTSearchCriteria.PUB_DATE:
                                    query = query.OrderBy("PublicationDate", false);
                                    break;
                                case DTSearchCriteria.TITLE:
                                    query = query.OrderBy("Title", false);
                                    break;
                            }
                        }

                        #endregion
                    }

                    result = query.ToList<Book>();
                    #endregion
                }
                else
                {
                    #region Normal Search
                    
                    var query =
                    from book in queryable
                     where
                       book.Keywords == SearchCriteria.mainKeywords
                     select book;

                    if (newSearch)
                    {
                        totalItems = query.Count<Book>();
                    }

                    query = query.Skip<Book>(numberItemsToSkip).Take<Book>(ITEMS_PER_PAGE);

                    result = query.ToList<Book>();
                    #endregion
                }

                // Set the advanced search to OFF, because when the first search is performed, advanced search windows is closed
                //advanced.isAdvanced = false;

                //TODO::Revisar como se puede hacer esto hay que obtener el enumerator para que se
                //popule la query o se hace asi o se recorre la query evaluen el cliente pidio que no se generara
                //otra lista con el contenido de la query
                //query.GetEnumerator();
                //result = query.ToList<Book>();

                //TODO:esto se tiene que ir
                //foreach (var item in query)
                //{
                //    result.Add((Common.DataTypes.Book)item);
                //    lstQueryResult.Add((Common.DataTypes.Book)item);
                //}

                //Invoque the event on the UiThread
                _mainDispatcher.BeginInvoke(delegate()
                {
                    //OnSearchCompleted(new SearchCompletedEventArgs(result));
                    //TODO::Arreglar problema de tipos que retorna y aarreglar
                    SearchCompleted(result);
                });
            }
            catch (Exception e)
            {
                //TODO:: ver de hacer manejo de la excepcion o sacar
                throw e;
            }
        }

        private void SearchCompleted(IEnumerable<Book> query)
        {
            lstResult.ItemsSource = query;
            if (newSearch & lstResult.Items.Count > 0)
            {
                lstResult.Visibility = Visibility.Visible;
                hlnkAdvSearch.Foreground = new SolidColorBrush(Colors.Black);
                InitializePagesInformation();
            }

            SBLoad.Pause();
            btnCloseMessage_Click(null, null);
            SBLoad.Stop();
            btnCloseMessage.Visibility = Visibility.Visible;
            PopUpBox.Visibility = Visibility.Visible;
            PopUpLoading.Visibility = Visibility.Collapsed;
        }


        Boolean newSearch;
        void Search_Click(object sender, EventArgs args)
        {
            advanced.isAdvanced = (uctrlAdvSearch.Visibility == Visibility.Visible);

            newSearch = true;
            actualPage = 1;
            totalPages = 1;
            totalItems = 0;
            if (advanced.isAdvanced)
            {
                advanced.author = uctrlAdvSearch.GetAuthor();
                advanced.title = uctrlAdvSearch.GetTitle();

                // Set the category
                advanced.category = uctrlAdvSearch.GetCategory();

                // Set the condition
                advanced.condition = uctrlAdvSearch.GetCondition();

                // Set min and max price
                //string textMaxPrice = uctrlAdvSearch.txtFilMaxPrice.Text;
                //int textPriceValueAux;
                //int.TryParse(uctrlAdvSearch.txtFilMaxPrice.Text, out textPriceValueAux);
                advanced.maxPrice = uctrlAdvSearch.GetMaxPrice();

                //int.TryParse(uctrlAdvSearch.txtFilMinPrice.Text, out textPriceValueAux);
                //advanced.minPrice = textPriceValueAux;
                advanced.maxPrice = uctrlAdvSearch.GetMinPrice();

                advanced.publisher = uctrlAdvSearch.GetPublisher();
                advanced.keywords = uctrlAdvSearch.GetKeyword();

                advanced.sortBy.isSortConditionSelected = (uctrlAdvSearch.GetSortFirst() != 0);
                advanced.sortBy.firstSortCondition = uctrlAdvSearch.GetSortFirst();

                advanced.sortBy.isSecondConditionSelected = (uctrlAdvSearch.GetSortSecond() != 0);
                advanced.sortBy.secondSortCondition = uctrlAdvSearch.GetSortSecond();

                advanced.sortBy.isThirdConditionSelected = (uctrlAdvSearch.GetSortThird() != 0);
                advanced.sortBy.thirdSortCondition = uctrlAdvSearch.GetSortThird();

                /******************************/
                uctrlAdvSearch.Visibility = Visibility.Collapsed;
                txtQuery.Visibility = Visibility.Visible;
                txtQuery.Text = uctrlAdvSearch.txtFilKeyword.Text;
                hlnkAdvSearch.Content = "Advanced Search";
                btnCloseMessage_Click(sender, null);

            }
            else
            {
                advanced.mainKeywords = this.txtQuery.Text;
            }
            SearcherFnc();
        }

        #endregion

        #region UI Methods
        void txtQueryKeyDown(object sender, KeyEventArgs e)
        {
            newSearch = true;
            actualPage = 1;
            totalPages = 1;
            totalItems = 0;
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                if (e.Key == System.Windows.Input.Key.Enter)
                {
                    advanced.mainKeywords = this.txtQuery.Text;
                    advanced.isAdvanced = false;
                    SearcherFnc();
                }

            }
        }

        Boolean showItemInfo = false;
        void ShowItemInformation(object sender, MouseButtonEventArgs e)
        {
            /*
             * The event SelectionChanged is executed before the event ShowItemInformation,
             * so at this moment we don't know which item contain the selected photo,
             * and for this reason here we simulate the event SelectionChanged.
             */
            showItemInfo = true;
            lstResultSelectionChanged(sender, null);
        }

        /***********************************************************************/
        void lstResultSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            List<Item> lst = new List<Item>();
            lst.Add((Item)lstResult.SelectedItem);
            icMoreInfoPopUp.ItemsSource = (IEnumerable<Item>)lst;
            if (showItemInfo)
            {
                PopUpLoading.Visibility = Visibility.Collapsed;//NEW
                PopUpBox.Visibility = Visibility.Visible;//NEW
                SignInPopUp.Visibility = Visibility.Collapsed;
                icMoreInfoPopUp.Visibility = Visibility.Visible;
                PopPup();
                Show();
                showItemInfo = false;
            }
        }

        void btnBooksToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrBooks");
            rdrBooks.CenterX = 30;
            rdrBooks.CenterY = 30;
            renderBigger.Begin();
        }

        void btnBooksToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrBooks");
            renderLower.Begin();
        }

        void btnAbout1ToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrAbout1");
            rdrAbout1.CenterX = 30;
            rdrAbout1.CenterY = 30;
            renderBigger.Begin();
        }

        void btnAbout1ToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrAbout1");
            renderLower.Begin();
        }

        void btnAbout2ToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrAbout2");
            rdrAbout2.CenterX = 30;
            rdrAbout2.CenterY = 30;
            renderBigger.Begin();
        }

        void btnAbout2ToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrAbout2");
            renderLower.Begin();
        }
        
        void Advanced(object sender, EventArgs args)
        {
            if (uctrlAdvSearch.Visibility == Visibility.Visible)
            {
                if (lstResult.Items.Count > 0)
                {
                    InformationVisbility(true);
                }
                uctrlAdvSearch.Visibility = Visibility.Collapsed;
                txtQuery.Visibility = Visibility.Visible;
                //hlnkAdvSearch.Content = "Advanced Search";
                btnCloseMessage_Click(sender, null);
                advanced.isAdvanced = false;
                txtQuery.Focus();
            }
            else
            {
                InformationVisbility(false);
                if (sender.GetType().Equals(hlnkAdvSearch.GetType()))
                {
                    uctrlAdvSearch.Visibility = Visibility.Visible;
                    txtQuery.Visibility = Visibility.Collapsed;
                    //hlnkAdvSearch.Content = "Basic Search";
                    advanced.isAdvanced = true;
                    uctrlAdvSearch.SetFocus();
                }
            }

            string Aux = ((string)hlnkAdvSearch.Content);
            hlnkAdvSearch.Content = hlnkAdvSearch.Tag.ToString();
            hlnkAdvSearch.Tag = Aux;


        }

        private void InformationVisbility(Boolean visible)
        {
            if (visible)
            {
                lstResult.Visibility = Visibility.Visible;
                lstResult.Visibility = Visibility.Visible;
                txtPagesInfoT.Visibility = Visibility.Visible;
                hlkFPageT.Visibility = Visibility.Visible;
                hlkPPageT.Visibility = Visibility.Visible;
                hlkNPageT.Visibility = Visibility.Visible;
                hlkLPageT.Visibility = Visibility.Visible;

                txtPagesInfoB.Visibility = Visibility.Visible;
                hlkFPageB.Visibility = Visibility.Visible;
                hlkPPageB.Visibility = Visibility.Visible;
                hlkNPageB.Visibility = Visibility.Visible;
                hlkLPageB.Visibility = Visibility.Visible;
            }
            else
            {
                lstResult.Visibility = Visibility.Collapsed;
                txtPagesInfoT.Visibility = Visibility.Collapsed;
                hlkFPageT.Visibility = Visibility.Collapsed;
                hlkPPageT.Visibility = Visibility.Collapsed;
                hlkNPageT.Visibility = Visibility.Collapsed;
                hlkLPageT.Visibility = Visibility.Collapsed;

                txtPagesInfoB.Visibility = Visibility.Collapsed;
                hlkFPageB.Visibility = Visibility.Collapsed;
                hlkPPageB.Visibility = Visibility.Collapsed;
                hlkNPageB.Visibility = Visibility.Collapsed;
                hlkLPageB.Visibility = Visibility.Collapsed;
            }
        }

        private void hlkSignIn_Click(object sender, RoutedEventArgs e)
        {
            hlkSignIn.Tag = passwordAmazon;
            recKey.Visibility = Visibility.Visible;
            SBKey.Begin();

            //Clean the Error Message
            txtMsgKeyPopUp.Text = "";


            // Create thread to perform the key validation
            Thread worker = new Thread(new ThreadStart(CheckQuery));
            worker.Start();
        }
        
        private void CheckQuery(){
            // Set the manual reset
            alldone = new ManualResetEvent(false);
            
            // Build the REST request
            
            StringBuilder baseURL = new StringBuilder("http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&AWSAccessKeyId=").Append(passwordAmazon).Append("&SearchIndex=Books&ResponseGroup=Medium&Keywords=harry");
            RestDataAccess da = new RestDataAccess(baseURL.ToString());
            da.RestRequestCompleted += new RestDataAccess.RestRequestCompletedHandler(da_RestRequestCompleted);
            da.PerformRestRequest();

            alldone.WaitOne();

            //Invoque the event on the UiThread
            _mainDispatcher.BeginInvoke(delegate()
            {
                //OnSearchCompleted(new SearchCompletedEventArgs(result));
                //TODO::Arreglar problema de tipos que retorna y aarreglar
                KeyValidationCompleted(validKey);
            });
        }

        private void KeyValidationCompleted(bool isKeyValid)
        {
            SBKey.Stop();
            recKey.Visibility = Visibility.Collapsed;
            if (isKeyValid)
            {
                SBLoad.Pause();
                btnCloseMessage_Click(null, null);
                SBLoad.Stop();
            }
            else
            {
                txtMsgKeyPopUp.Text = txtMsgKeyPopUp.Tag.ToString();
                txtKeyPopUp.Text = "";
                passwordAmazon = "";
                //pwdAmazonKey.Password = "";
                //passwordAmazon.Remove(0, passwordAmazon.Length);
            }
        }

        // Parse key validation response and set the key state (true or false)
        static void da_RestRequestCompleted(object sender, RestRequestCompletedEventArgs e)
        {
            //Handle the Key query result
            try
            {
                XmlReader xmlReader = XmlReader.Create(new StringReader(e.Result));

                XmlSerializer xSerializer = new XmlSerializer(typeof(Common.DataTypes.AmazonKeyQueryParser));

                Common.DataTypes.AmazonKeyQueryParser queryParser = (AmazonKeyQueryParser)xSerializer.Deserialize(xmlReader);

                // Set if the key is valid or not
                validKey = queryParser.IsValidKey();

                alldone.Set();
            }
            catch (Exception excep)
            {
            }
        }

        private void hlkSignInAgain_Click(object sender, RoutedEventArgs e)
        {
            txtKeyPopUp.Text = passwordAmazon;
            txtKeyPopUp.SelectionStart = 1;
            
            PopUpKey.Visibility = Visibility.Visible;
            PopUpKeyContent.Visibility = Visibility.Visible;
            btnKeyClose.Visibility = Visibility.Visible;
            PopUpBox.Visibility = Visibility.Collapsed;

            //btnCloseMessage.Visibility = Visibility.Visible;
            //icMoreInfoPopUp.Visibility = Visibility.Collapsed;
            SignInPopUp.Visibility = Visibility.Visible;
            PopPup();
            Show();
        }
        #endregion

        #region Language

        void ChangeLanguage(object sender, EventArgs args)
        {            
            language = (language == 1) ? 2 : 1;
            SetLanguage();
            SearcherFnc();

        }
        
        private void SetLanguage()
        {
            TextLanguage textL = new TextLanguage();

            hlkSignIn.Content = textL.GetText(TextLanguage.fields.key_change_used, language);
            btnSearch.Content = textL.GetText(TextLanguage.fields.search, language);

            if (uctrlAdvSearch.Visibility == Visibility.Visible)
            {
                hlnkAdvSearch.Content = textL.GetText(TextLanguage.fields.lnksearch_basic, language);
                hlnkAdvSearch.Tag = textL.GetText(TextLanguage.fields.lnksearch_advanced, language);
            }
            else
            {                
                hlnkAdvSearch.Content = textL.GetText(TextLanguage.fields.lnksearch_advanced, language);
                hlnkAdvSearch.Tag = textL.GetText(TextLanguage.fields.lnksearch_basic, language);
            }
            
            txtAmazonKeyPopUp.Text = textL.GetText(TextLanguage.fields.key_title, language);
            hlkSignInPopUp.Content = textL.GetText(TextLanguage.fields.key_signin, language);

            //Paginated - of
            txtPagesInfoB.Tag = textL.GetText(TextLanguage.fields.adv_pag_of, language);
            if (txtPagesInfoT.Tag != null)
            {
                txtPagesInfoT.Text = ((string)txtPagesInfoT.Tag).Replace("[p]", txtPagesInfoB.Tag.ToString());
                txtPagesInfoB.Text = txtPagesInfoT.Text;
            }

            // It shows the appropriate photo
            imgEEUU.Visibility = (language == 2) ? Visibility.Visible : Visibility.Collapsed;
            imgES.Visibility = (language == 1) ? Visibility.Visible : Visibility.Collapsed;

            //Loading
            lblLoading.Text = textL.GetText(TextLanguage.fields.adv_loading, language);

            //Invalid key
            txtMsgKeyPopUp.Tag = textL.GetText(TextLanguage.fields.invalidkey, language);

            //Advanced Search
            uctrlAdvSearch.SetLanguage(language);
        }        

        #endregion
        
        #region Password

        void txtKey_KeyDown(object sender, KeyEventArgs args)
        {
            if (args.Key == System.Windows.Input.Key.Enter)
            {
                hlkSignIn_Click(null, null);
            }
            else
            {
                //passwordChanged = true;
            }
        }
        
        void txtKey_TextChanged(object sender, TextChangedEventArgs args)
        {
            if (passwordChanged)
            {
                if (SignInPopUp.Visibility == Visibility.Visible)
                {
                    int Index = txtKeyPopUp.SelectionStart;

                    int Rest = txtKeyPopUp.Text.Length - passwordAmazon.Length;

                    if (Rest > 0)
                    {
                        passwordAmazon = passwordAmazon.Insert(txtKeyPopUp.SelectionStart - Rest, txtKeyPopUp.Text.Substring(txtKeyPopUp.SelectionStart - Rest, Rest));
                    }
                    else if (Rest == 0)
                    {
                        if (passwordAmazon.Length > 0)
                        {
                            passwordAmazon = passwordAmazon.Substring(0, txtKeyPopUp.SelectionStart - 1)
                                          + txtKeyPopUp.Text.Substring(txtKeyPopUp.SelectionStart - 1, 1)
                                          + passwordAmazon.Substring(txtKeyPopUp.SelectionStart, passwordAmazon.Length - txtKeyPopUp.SelectionStart);
                        }
                    }
                    else
                    {
                        Rest = Rest * -1;
                        passwordAmazon = passwordAmazon.Remove(txtKeyPopUp.SelectionStart, Rest);                    
                    }

                    
                    string Aux = txtKeyPopUp.Text;
                    txtKeyPopUp.Text = new string('*', txtKeyPopUp.Text.Length);
                    if (Aux != txtKeyPopUp.Text)
                    {
                        passwordChanged = false;
                    }
                    txtKeyPopUp.SelectionStart = Index;                
                }
            }
            else
            {
                passwordChanged = true;
            }
        }

        #endregion
        
        #region Paginated

        private void InitializePagesInformation()
        {
            if (totalItems == 0)
            {
                TextLanguage textL = new TextLanguage();
                txtPagesInfoT.Text = textL.GetText(TextLanguage.fields.adv_pag_noresult, language);
            }
            else
            {
                actualPage = 1;

                if (totalItems <= ITEMS_PER_PAGE)
                {
                    totalPages = 1;
                    RefreshTxtPages(1, totalItems);

                    txtPagesInfoT.Visibility = Visibility.Visible;
                    txtPagesInfoB.Visibility = Visibility.Visible;
                }
                else
                {
                    if (totalItems > 100)
                    {
                        totalItems = 100;
                    }

                    totalPages = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(totalItems) / ITEMS_PER_PAGE));

                    RefreshTxtPages(1, ITEMS_PER_PAGE);

                    txtPagesInfoT.Visibility = Visibility.Visible;
                    hlkFPageT.Visibility = Visibility.Collapsed;
                    hlkPPageT.Visibility = Visibility.Collapsed;
                    hlkNPageT.Visibility = Visibility.Visible;
                    hlkLPageT.Visibility = Visibility.Visible;

                    txtPagesInfoB.Visibility = Visibility.Visible;
                    hlkFPageB.Visibility = Visibility.Collapsed;
                    hlkPPageB.Visibility = Visibility.Collapsed;
                    hlkNPageB.Visibility = Visibility.Visible;
                    hlkLPageB.Visibility = Visibility.Visible;
                }
            }
        }

        private void hlkFPage_Click(object sender, RoutedEventArgs e)
        {
            newSearch = false;
            actualPage = 1;
            SearcherFnc();

            // Calculate the last item of the first page. It's the lower between ITEMS_PER_PAGE and the number of items of the result
            int to = Convert.ToInt32(Math.Min(ITEMS_PER_PAGE, totalItems));

            RefreshTxtPages(1, to);

            hlkFPageT.Visibility = Visibility.Collapsed;
            hlkPPageT.Visibility = Visibility.Collapsed;
            hlkNPageT.Visibility = Visibility.Visible;
            hlkLPageT.Visibility = Visibility.Visible;

            hlkFPageB.Visibility = Visibility.Collapsed;
            hlkPPageB.Visibility = Visibility.Collapsed;
            hlkNPageB.Visibility = Visibility.Visible;
            hlkLPageB.Visibility = Visibility.Visible;
        }
        
        private void hlkPPage_Click(object sender, RoutedEventArgs e)
        {
            newSearch = false;
            actualPage -= 1;
            SearcherFnc();

            int from = ((actualPage - 1) * ITEMS_PER_PAGE) + 1;
            int to = actualPage * ITEMS_PER_PAGE;

            hlkNPageT.Visibility = Visibility.Visible;
            hlkLPageT.Visibility = Visibility.Visible;
            hlkNPageB.Visibility = Visibility.Visible;
            hlkLPageB.Visibility = Visibility.Visible;

            if (actualPage == 1)
            {
                hlkFPageT.Visibility = Visibility.Collapsed;
                hlkPPageT.Visibility = Visibility.Collapsed;
                hlkFPageB.Visibility = Visibility.Collapsed;
                hlkPPageB.Visibility = Visibility.Collapsed;
            }

            RefreshTxtPages(from, to);
        }

        private void hlkNPage_Click(object sender, RoutedEventArgs e)
        {
            newSearch = false;
            actualPage += 1;
            SearcherFnc();

            int from = ((actualPage - 1) * ITEMS_PER_PAGE) + 1;
            int to = actualPage * ITEMS_PER_PAGE;

            hlkFPageT.Visibility = Visibility.Visible;
            hlkPPageT.Visibility = Visibility.Visible;
            hlkFPageB.Visibility = Visibility.Visible;
            hlkPPageB.Visibility = Visibility.Visible;

            if (actualPage == totalPages)
            {
                to = totalItems;
                hlkNPageT.Visibility = Visibility.Collapsed;
                hlkLPageT.Visibility = Visibility.Collapsed;
                hlkNPageB.Visibility = Visibility.Collapsed;
                hlkLPageB.Visibility = Visibility.Collapsed;
            }

            RefreshTxtPages(from, to);
        }

        private void hlkLPage_Click(object sender, RoutedEventArgs e)
        {
            newSearch = false;
            actualPage = totalPages;
            SearcherFnc();

            int from = ((actualPage - 1) * ITEMS_PER_PAGE) + 1;
            int to = from + ((totalItems - 1) % ITEMS_PER_PAGE);

            hlkFPageT.Visibility = Visibility.Visible;
            hlkPPageT.Visibility = Visibility.Visible;
            hlkFPageB.Visibility = Visibility.Visible;
            hlkPPageB.Visibility = Visibility.Visible;

            hlkNPageT.Visibility = Visibility.Collapsed;
            hlkLPageT.Visibility = Visibility.Collapsed;
            hlkNPageB.Visibility = Visibility.Collapsed;
            hlkLPageB.Visibility = Visibility.Collapsed;

            RefreshTxtPages(from, to);
        }

        private void RefreshTxtPages(int from, int to)
        {
            txtPagesInfoT.Tag = " " + from.ToString() + "-" + to.ToString() + " " +
                                 "[p]" + " " + totalItems.ToString() + " ";

            txtPagesInfoT.Text = ((string)txtPagesInfoT.Tag).Replace("[p]", txtPagesInfoB.Tag.ToString());
            txtPagesInfoB.Text = txtPagesInfoT.Text;
        }

        #region First,Previous,Next,Last
        private void hlkFPageT_MouseEnter(object sender, MouseEventArgs e)
        {
            imgFirstT.Source = new BitmapImage(new Uri("images/First.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkFPageT_MouseLeave(object sender, MouseEventArgs e)
        {
            imgFirstT.Source = new BitmapImage(new Uri("images/FirstT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkPPageT_MouseEnter(object sender, MouseEventArgs e)
        {
            imgPreviousT.Source = new BitmapImage(new Uri("images/Previous.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkPPageT_MouseLeave(object sender, MouseEventArgs e)
        {
            imgPreviousT.Source = new BitmapImage(new Uri("images/PreviousT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkNPageT_MouseEnter(object sender, MouseEventArgs e)
        {
            imgNextT.Source = new BitmapImage(new Uri("images/Next.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkNPageT_MouseLeave(object sender, MouseEventArgs e)
        {
            imgNextT.Source = new BitmapImage(new Uri("images/NextT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkLPageT_MouseEnter(object sender, MouseEventArgs e)
        {
            imgLastT.Source = new BitmapImage(new Uri("images/Last.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkLPageT_MouseLeave(object sender, MouseEventArgs e)
        {
            imgLastT.Source = new BitmapImage(new Uri("images/LastT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkFPageB_MouseEnter(object sender, MouseEventArgs e)
        {
            imgFirstB.Source = new BitmapImage(new Uri("images/FirstT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkFPageB_MouseLeave(object sender, MouseEventArgs e)
        {
            imgFirstB.Source = new BitmapImage(new Uri("images/First.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkPPageB_MouseEnter(object sender, MouseEventArgs e)
        {
            imgPreviousB.Source = new BitmapImage(new Uri("images/PreviousT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkPPageB_MouseLeave(object sender, MouseEventArgs e)
        {
            imgPreviousB.Source = new BitmapImage(new Uri("images/Previous.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkNPageB_MouseEnter(object sender, MouseEventArgs e)
        {
            imgNextB.Source = new BitmapImage(new Uri("images/NextT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkNPageB_MouseLeave(object sender, MouseEventArgs e)
        {
            imgNextB.Source = new BitmapImage(new Uri("images/Next.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkLPageB_MouseEnter(object sender, MouseEventArgs e)
        {
            imgLastB.Source = new BitmapImage(new Uri("images/LastT.jpg", UriKind.RelativeOrAbsolute));
        }

        private void hlkLPageB_MouseLeave(object sender, MouseEventArgs e)
        {
            imgLastB.Source = new BitmapImage(new Uri("images/Last.jpg", UriKind.RelativeOrAbsolute));
        }
        #endregion

        #endregion

        #region PopUp

        public void PopPup()
        {
            App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
            backGround.Width = LayoutRoot.ActualWidth;
            backGround.Height = LayoutRoot.ActualHeight;
        }

        void Content_Resized(object sender, EventArgs e)
        {
            backGround.Width = LayoutRoot.ActualWidth;
            backGround.Height = LayoutRoot.ActualHeight;
        }


        void btnCloseMessage_Click(object sender, RoutedEventArgs e)
        {
            closeMessage.Begin();
            PopUpKeyContent.Visibility = Visibility.Collapsed;
            BaseLayoutRoot.Visibility = Visibility.Visible;
            BrdLayoutRoot.Visibility = Visibility.Visible;
        }

        void btnKeyClose_Click(object sender, RoutedEventArgs e)
        {
            passwordAmazon = hlkSignIn.Tag.ToString();
            closeMessage.Begin();
            PopUpKeyContent.Visibility = Visibility.Collapsed;
            BaseLayoutRoot.Visibility = Visibility.Visible;
            BrdLayoutRoot.Visibility = Visibility.Visible;
        }

        public void Close()
        {
            popUpMessage.IsOpen = false;
            backGround.Visibility = Visibility.Collapsed;
        }

        public void Show()
        {
            Point p = new Point();

            if (PopUpBox.Visibility == Visibility.Visible)
            {
                p.X = App.Current.Host.Content.ActualWidth / 4;
                p.Y = (App.Current.Host.Content.ActualHeight / 2) - 125;
            }
            else if (PopUpKey.Visibility == Visibility.Visible)
            {
                p.X = App.Current.Host.Content.ActualWidth / 3;
                p.Y = App.Current.Host.Content.ActualHeight / 3;
            }
            else
            {
                p.X = App.Current.Host.Content.ActualWidth / 3;
                p.Y = App.Current.Host.Content.ActualHeight / 3;
            }
            if (showItemInfo)
            {
                scrlGral.ScrollToVerticalOffset(scrlGral.ScrollableHeight / 2);
                p.Y = (App.Current.Host.Content.ActualHeight / 2);
            }

            if (PopUpBox.Visibility == Visibility.Visible)
            {
                icMoreInfoPopUp.Focus();
                PopUpBox.Margin = new Thickness(p.X, p.Y, 0, 0);
            }
            else if (PopUpKey.Visibility == Visibility.Visible)
            {
                PopUpKey.Margin = new Thickness(p.X, p.Y, 0, 0);
            }
            else
            {
                PopUpLoading.Margin = new Thickness(p.X, p.Y, 0, 0);

            }
            /*
            if (PopUpLoading.Visibility == Visibility.Collapsed)
            {
                p.X = App.Current.Host.Content.ActualWidth / 4;
                p.Y = (App.Current.Host.Content.ActualHeight / 2) - 125;
            }
            else
            {
                p.X = App.Current.Host.Content.ActualWidth / 3;
                p.Y = App.Current.Host.Content.ActualHeight / 3;
            }
            if (showItemInfo)
            {
                scrlGral.ScrollToVerticalOffset(scrlGral.ScrollableHeight / 2);
                p.Y = (App.Current.Host.Content.ActualHeight / 2);
            }

            if (PopUpBox.Visibility == Visibility.Visible)
            {
                icMoreInfoPopUp.Focus();
                PopUpBox.Margin = new Thickness(p.X, p.Y, 0, 0);
            }
            else
            {
                PopUpLoading.Margin = new Thickness(p.X, p.Y, 0, 0);
            }
            */
            popUpMessage.IsOpen = true;
            backGround.Visibility = Visibility.Visible;
            openMessage.Completed += (s, e) =>
            {
                btnCloseMessage.Focus();
            };
            openMessage.Begin();
        }

        #endregion

        private void ResultSearch_Loaded(object sender, RoutedEventArgs e)
        {
            TextLanguage textL = new TextLanguage();
            ((TextBlock)sender).Text = textL.GetTextItemResult(((TextBlock)sender).Name, language);
        }

    }

}
